package State;

import bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author Spring_Hu
 * @date 2021/10/15 20:42
 */
public class KeyByed_state_AggregatingState {
    //键控 aggregate aggregate与reduce的区别为aggregate输入输出类型可以不一致
    //输出 水位的平均值
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.enableCheckpointing(2000L, CheckpointingMode.EXACTLY_ONCE);


        SingleOutputStreamOperator<WaterSensor> source = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] line = value.split(",");
                        return new WaterSensor(
                                line[0],
                                Long.parseLong(line[1]),
                                Integer.parseInt(line[2]));
                    }
                })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                            @Override
                            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                return element.getTs()*1000L;
                            }
                        }));

        source.keyBy(value -> value.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    //声明使用的键控state为aggregate类型
                   AggregatingState<Integer,Double> aggstate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //初始化状态
                        AggregatingStateDescriptor<Integer, Tuple2<Integer, Integer>, Double> aggregatingStateDescriptor = new AggregatingStateDescriptor<Integer, Tuple2<Integer, Integer>, Double>("avgState",
                                new AggregateFunction<Integer, Tuple2<Integer, Integer>, Double>(){

                                    @Override
                                    //初始化缓存
                                    public Tuple2<Integer, Integer> createAccumulator() {
                                        return Tuple2.of(0,0);
                                    }

                                    @Override
                                    //累加
                                    public Tuple2<Integer, Integer> add(Integer value, Tuple2<Integer, Integer> accumulator) {
                                        return Tuple2.of(accumulator.f0+value,accumulator.f1+1);
                                    }

                                    @Override
                                    //获取结果
                                    public Double getResult(Tuple2<Integer, Integer> accumulator) {
                                        return accumulator.f0*1.0d/accumulator.f1 ;
                                    }

                                    @Override
                                    public Tuple2<Integer, Integer> merge(Tuple2<Integer, Integer> a, Tuple2<Integer, Integer> b) {
                                        return null;
                                    }
                                },Types.TUPLE(Types.INT, Types.INT));
                        aggstate=getRuntimeContext().getAggregatingState(aggregatingStateDescriptor);
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        aggstate.add(value.getVc());
                        out.collect("输出结果为："+aggstate.get());
                    }
                }).print();

        env.execute();
    }


}
